package com.charley.icloud.eureka.listener;

import com.netflix.appinfo.InstanceInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * Eureka 状态监听器
 */
@Slf4j
//@Component
public class EurekaStateChangeListener {

    private final static Boolean isWindows = System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("win");

    private Map<String, Boolean> map;

    /**
     * @param event Eureka 服务实例被取消注册的事件
     */
    @EventListener
    public void listen(EurekaInstanceCanceledEvent event) {
        log.info("Eureka 服务实例被取消注册的事件:" + event.toString());
    }

    /**
     * @param event 服务注册事件
     */
    @EventListener
    public void listen(EurekaInstanceRegisteredEvent event) {
        InstanceInfo info = event.getInstanceInfo();
        if (isWindows && InstanceInfo.InstanceStatus.UP.equals(info.getStatus())) {
            log.info("服务上线事件【" + info.getAppName() + "在" + info.getHostName() + "上线】");
            message(info.getHostName(), "服务上线事件【" + info.getAppName() + "在" + info.getHostName() + "上线】");
        } else if (isWindows && InstanceInfo.InstanceStatus.DOWN.equals(info.getStatus())) {
            log.info("服务下线事件【" + info.getAppName() + "在" + info.getHostName() + "下线】");
            message(info.getHostName(), "服务下线事件【" + info.getAppName() + "在" + info.getHostName() + "下线】");
        }
    }

    /**
     * @param event 服务续约事件
     */
    @EventListener
    public void listen(EurekaInstanceRenewedEvent event) {
        InstanceInfo info = event.getInstanceInfo();
        log.info("服务续约事件:" + info.getAppName() + "续约");
    }

    /**
     * @param event Eureka 服务注册中心可用事件
     */
    @EventListener
    public void listen(EurekaRegistryAvailableEvent event) {
        //log.info("服务注册中心可用事件:"+event.toString());
    }

    /**
     * @param event 注册中心启动事件
     */
    @EventListener
    public void listen(EurekaServerStartedEvent event) {
        log.info("注册中心启动事件:" + event.toString());
        if (isWindows) {
            message("注册中心启动事件:");
        }
    }

    @PreDestroy
    public void shutdown() {
        log.info("注册中心服务关闭");
        if (isWindows) {
            message("注册中心服务关闭");
        }
    }

    public void message(String ip, String msg) {
        if (null == this.map) {
            String[] arr = ip.split(",");
            this.map = new HashMap<>();
            for (int i = 0; arr.length != 0 && i < arr.length; i++) {
                this.map.put(arr[i], Boolean.TRUE);
            }
        }

        if (!this.map.containsKey(ip)) {
            System.out.println(msg);
        }
    }

    public void message(String msg) {
        message(null, msg);
    }
}
